<template>
  <div class="network-page">
    <div class="page-header">
      <div class="header-content">
        <h2>网络关系可视化</h2>
        <p>可视化展示生命体之间的关系网络和交互模式</p>
      </div>
      <div class="header-actions">
        <a-space>
          <a-button @click="refreshData" :loading="loading">
            <template #icon><reload-outlined /></template>
            刷新数据
          </a-button>
          <a-button @click="showCreateRelationship" type="primary">
            <template #icon><plus-outlined /></template>
            创建关系
          </a-button>
        </a-space>
      </div>
    </div>

    <!-- 网络图表 -->
    <a-card :bordered="false" class="network-card">
      <template #title>
        <a-space>
          <share-alt-outlined />
          关系网络图
        </a-space>
      </template>
      <template #extra>
        <a-space>
          <a-select
            v-model:value="graphLibrary"
            size="small"
            style="width: 100px"
            @change="handleGraphLibraryChange"
          >
            <a-select-option value="echarts">ECharts</a-select-option>
            <a-select-option value="g6">G6</a-select-option>
          </a-select>
          <a-select
            v-model:value="viewMode"
            size="small"
            style="width: 120px"
            @change="handleViewModeChange"
          >
            <a-select-option value="full">完整网络</a-select-option>
            <a-select-option value="strong">强关系</a-select-option>
            <a-select-option value="type">按类型</a-select-option>
          </a-select>
          <a-button size="small" @click="exportNetwork">
            <template #icon><download-outlined /></template>
            导出
          </a-button>
        </a-space>
      </template>

      <div class="network-container">
        <EChartsNetworkGraph
          v-if="graphLibrary === 'echarts'"
          ref="networkGraphRef"
          :data="networkData"
          :width="graphWidth"
          :height="graphHeight"
          @node-click="handleNodeClick"
          @edge-click="handleEdgeClick"
          @node-double-click="handleNodeDoubleClick"
          @canvas-click="handleCanvasClick"
        />
        <G6NetworkGraph
          v-else-if="graphLibrary === 'g6'"
          ref="networkGraphRef"
          :data="networkData"
          :width="graphWidth"
          :height="graphHeight"
          @node-click="handleNodeClick"
          @edge-click="handleEdgeClick"
          @node-double-click="handleNodeDoubleClick"
          @canvas-click="handleCanvasClick"
        />
      </div>
    </a-card>

    <!-- 网络统计 -->
    <a-card :bordered="false" class="statistics-card">
      <template #title>
        <a-space>
          <bar-chart-outlined />
          网络统计分析
        </a-space>
      </template>
      <template #extra>
        <a-button size="small" @click="exportStatistics">
          <template #icon><download-outlined /></template>
          导出统计
        </a-button>
      </template>

      <NetworkStatistics
        :statistics="networkStatistics"
        :node-data="networkData.nodes"
        :edge-data="networkData.edges"
      />
    </a-card>

    <!-- 关系详情弹窗 -->
    <RelationshipModal
      v-model:visible="relationshipModalVisible"
      :relationship="selectedRelationship"
      @updated="handleRelationshipUpdated"
      @deleted="handleRelationshipDeleted"
    />

    <!-- 创建关系弹窗 -->
    <a-modal
      v-model:open="createRelationshipVisible"
      title="创建新关系"
      :width="600"
      @ok="handleCreateRelationship"
      @cancel="resetCreateForm"
      :confirm-loading="creating"
    >
      <a-form
        ref="createFormRef"
        :model="createForm"
        :rules="createFormRules"
        layout="vertical"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="源实体" name="sourceEntityId">
              <a-select
                v-model:value="createForm.sourceEntityId"
                placeholder="选择源实体"
                show-search
                :filter-option="filterOption"
              >
                <a-select-option
                  v-for="entity in availableEntities"
                  :key="entity.id"
                  :value="entity.id"
                >
                  {{ entity.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="目标实体" name="targetEntityId">
              <a-select
                v-model:value="createForm.targetEntityId"
                placeholder="选择目标实体"
                show-search
                :filter-option="filterOption"
              >
                <a-select-option
                  v-for="entity in availableEntities"
                  :key="entity.id"
                  :value="entity.id"
                >
                  {{ entity.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="关系类型" name="relationshipType">
              <a-select
                v-model:value="createForm.relationshipType"
                placeholder="选择关系类型"
              >
                <a-select-option value="COLLABORATION">协作</a-select-option>
                <a-select-option value="COMPETITION">竞争</a-select-option>
                <a-select-option value="DEPENDENCY">依赖</a-select-option>
                <a-select-option value="FUSION">融合</a-select-option>
                <a-select-option value="COMMUNICATION">通信</a-select-option>
                <a-select-option value="INHERITANCE">继承</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="关系强度" name="strength">
              <a-slider
                v-model:value="createForm.strength"
                :min="0"
                :max="1"
                :step="0.1"
                :tooltip-formatter="(value: number) => `${(value * 100).toFixed(0)}%`"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="描述" name="description">
          <a-textarea
            v-model:value="createForm.description"
            placeholder="请输入关系描述"
            :rows="3"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { message } from 'ant-design-vue'
import {
  ReloadOutlined,
  PlusOutlined,
  ShareAltOutlined,
  BarChartOutlined,
  DownloadOutlined
} from '@ant-design/icons-vue'
import { networkApi } from '@/api/network'
import { lifeEntityApi } from '@/api/lifeEntity'
import EChartsNetworkGraph from '@/components/NetworkGraph/EChartsNetworkGraph.vue'
import G6NetworkGraph from '@/components/NetworkGraph/G6NetworkGraph.vue'
import NetworkStatistics from '@/components/NetworkGraph/NetworkStatistics.vue'
import RelationshipModal from '@/components/NetworkGraph/RelationshipModal.vue'
import type { NetworkVisualizationData, LifeEntityRelationship, LifeEntity } from '@/api/types'

// 响应式数据
const loading = ref(false)
const viewMode = ref('full')
const graphLibrary = ref('echarts') // 新增：图形库选择
const networkGraphRef = ref()
const relationshipModalVisible = ref(false)
const createRelationshipVisible = ref(false)
const creating = ref(false)
const createFormRef = ref()

// 网络数据
const networkData = ref<NetworkVisualizationData>({
  nodes: [],
  edges: []
})

// 网络统计数据
const networkStatistics = ref({
  totalNodes: 0,
  totalEdges: 0,
  averageDegree: 0,
  networkDensity: 0,
  clusteringCoefficient: 0,
  connectedComponents: 1,
  averagePathLength: 0,
  networkDiameter: 0,
  communities: [] as any[],
  centralityRankings: [] as any[]
})

// 选中的关系
const selectedRelationship = ref<LifeEntityRelationship | null>(null)

// 可用实体列表
const availableEntities = ref<LifeEntity[]>([])

// 创建关系表单
const createForm = ref({
  sourceEntityId: '',
  targetEntityId: '',
  relationshipType: '',
  strength: 0.5,
  description: ''
})

// 创建表单验证规则
const createFormRules = {
  sourceEntityId: [
    { required: true, message: '请选择源实体' }
  ],
  targetEntityId: [
    { required: true, message: '请选择目标实体' }
  ],
  relationshipType: [
    { required: true, message: '请选择关系类型' }
  ]
}

// 计算属性
const graphWidth = computed(() => {
  return window.innerWidth - 100 // 减去侧边栏和边距
})

const graphHeight = computed(() => {
  return 600 // 固定高度
})

// 方法
const loadNetworkData = async () => {
  try {
    loading.value = true
    
    let data: NetworkVisualizationData
    
    switch (viewMode.value) {
      case 'strong':
        data = await networkApi.getStrongRelationshipNetwork()
        break
      case 'type':
        // 这里可以根据需要选择特定类型
        data = await networkApi.getNetworkVisualizationByType('COLLABORATION')
        break
      default:
        data = await networkApi.getVisualizationData()
    }
    
    networkData.value = data
    
    // 更新统计数据（从后端获取或计算）
    networkStatistics.value = {
      totalNodes: data.nodes.length,
      totalEdges: data.edges.length,
      averageDegree: data.edges.length > 0 ? (data.edges.length * 2) / data.nodes.length : 0,
      networkDensity: data.nodes.length > 1 ? (data.edges.length * 2) / (data.nodes.length * (data.nodes.length - 1)) : 0,
      clusteringCoefficient: Math.random() * 0.3 + 0.4, // 模拟数据
      connectedComponents: 1,
      averagePathLength: Math.log(data.nodes.length) * 1.5,
      networkDiameter: Math.log(data.nodes.length) * 2,
      communities: generateMockCommunities(data.nodes.length),
      centralityRankings: generateMockCentralityRankings(data.nodes)
    }
    
    message.success('网络数据加载完成')
  } catch (error) {
    message.error('加载网络数据失败')
    console.error('网络数据加载错误:', error)
  } finally {
    loading.value = false
  }
}

const loadAvailableEntities = async () => {
  try {
    const entities = await lifeEntityApi.getList({ size: 1000 })
    availableEntities.value = entities.content
  } catch (error) {
    message.error('加载实体列表失败')
  }
}

const refreshData = () => {
  loadNetworkData()
}

const handleViewModeChange = (mode: string) => {
  viewMode.value = mode
  loadNetworkData()
}

const handleGraphLibraryChange = (library: string) => {
  graphLibrary.value = library
  message.success(`已切换到 ${library === 'echarts' ? 'ECharts' : 'G6'} 图形库`)
}

const handleNodeClick = (node: any) => {
  console.log('节点点击:', node)
  message.info(`点击节点: ${node.name}`)
}

const handleEdgeClick = async (edge: any) => {
  try {
    // 获取关系详情
    const relationships = await networkApi.getRelationships({
      sourceEntityId: edge.source,
      targetEntityId: edge.target
    })
    
    if (relationships.length > 0) {
      selectedRelationship.value = relationships[0]
      relationshipModalVisible.value = true
    }
  } catch (error) {
    message.error('获取关系详情失败')
  }
}

const handleNodeDoubleClick = (node: any) => {
  console.log('节点双击:', node)
  // 可以跳转到节点详情页面
}

const handleCanvasClick = () => {
  // 清除选择状态
  selectedRelationship.value = null
}

const showCreateRelationship = () => {
  loadAvailableEntities()
  createRelationshipVisible.value = true
}

const handleCreateRelationship = async () => {
  try {
    await createFormRef.value.validate()
    creating.value = true
    
    await networkApi.createRelationship(createForm.value)
    
    message.success('关系创建成功')
    createRelationshipVisible.value = false
    resetCreateForm()
    loadNetworkData() // 重新加载数据
  } catch (error) {
    message.error('关系创建失败')
  } finally {
    creating.value = false
  }
}

const resetCreateForm = () => {
  createForm.value = {
    sourceEntityId: '',
    targetEntityId: '',
    relationshipType: '',
    strength: 0.5,
    description: ''
  }
}

const handleRelationshipUpdated = (relationship: LifeEntityRelationship) => {
  message.success('关系更新成功')
  loadNetworkData() // 重新加载数据
}

const handleRelationshipDeleted = (relationshipId: string) => {
  message.success('关系删除成功')
  loadNetworkData() // 重新加载数据
}

const exportNetwork = () => {
  // 导出网络图
  const dataStr = JSON.stringify(networkData.value, null, 2)
  const dataBlob = new Blob([dataStr], { type: 'application/json' })
  const url = URL.createObjectURL(dataBlob)
  const link = document.createElement('a')
  link.href = url
  link.download = `network-data-${new Date().toISOString().split('T')[0]}.json`
  link.click()
  URL.revokeObjectURL(url)
  message.success('网络数据导出成功')
}

const exportStatistics = () => {
  // 导出统计数据
  const dataStr = JSON.stringify(networkStatistics.value, null, 2)
  const dataBlob = new Blob([dataStr], { type: 'application/json' })
  const url = URL.createObjectURL(dataBlob)
  const link = document.createElement('a')
  link.href = url
  link.download = `network-statistics-${new Date().toISOString().split('T')[0]}.json`
  link.click()
  URL.revokeObjectURL(url)
  message.success('统计数据导出成功')
}

const filterOption = (input: string, option: any) => {
  return option.children.toLowerCase().includes(input.toLowerCase())
}

// 生成模拟社区数据
const generateMockCommunities = (nodeCount: number) => {
  const communityCount = Math.min(5, Math.max(2, Math.floor(nodeCount / 10)))
  const colors = ['#1890ff', '#52c41a', '#722ed1', '#fa8c16', '#eb2f96']
  
  return Array.from({ length: communityCount }, (_, i) => ({
    communityId: i + 1,
    communityName: `社区 ${i + 1}`,
    nodeCount: Math.floor(nodeCount / communityCount) + Math.floor(Math.random() * 5),
    nodeIds: [],
    modularity: Math.random() * 0.3 + 0.4,
    color: colors[i % colors.length]
  }))
}

// 生成模拟中心性排名数据
const generateMockCentralityRankings = (nodes: unknown[]) => {
  return nodes.slice(0, 20).map((node, index) => ({
    nodeId: node.id,
    nodeName: node.name,
    degreeCentrality: Math.random() * 0.8 + 0.2,
    betweennessCentrality: Math.random() * 0.6 + 0.1,
    closenessCentrality: Math.random() * 0.7 + 0.3,
    eigenvectorCentrality: Math.random() * 0.9 + 0.1,
    rank: index + 1
  }))
}

onMounted(() => {
  loadNetworkData()
})

onUnmounted(() => {
  // 清理资源
})
</script>

<style scoped>
.network-page {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
}

.header-content h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
}

.header-content p {
  margin: 0;
  color: #666;
}

.header-actions {
  flex-shrink: 0;
}

.network-card {
  margin-bottom: 24px;
}

.network-container {
  position: relative;
  height: 600px;
  width: 100%;
}

.statistics-card {
  margin-bottom: 24px;
}

:deep(.ant-card-head-title) {
  display: flex;
  align-items: center;
  gap: 8px;
}

:deep(.ant-card-extra) {
  display: flex;
  align-items: center;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
  }
  
  .header-actions {
    width: 100%;
  }
  
  .network-container {
    height: 400px;
  }
}
</style>
